import {App} from 'ant-design-vue';

export default function useRecord(props:any){
	/* speech SpeechRecognition不能兼容H5端，方案废除，使用MediaRecorder*/
	/* data */
	const { message } = App.useApp();
	let mediaRecorder:any =null;
	let recordedChunks:any[] = [];
	//是否正在录音？
	const recording = ref(false);

	let cbFinish: ((str:string)=>void) | undefined = undefined

	/* computed */
	//sender组件中，录音功能设置项
	const speechOption = computed(()=>{
		return props.uploadSpeechEnable? {
			recording: recording.value,
			onRecordingChange: (nextRecording:boolean) => {
				if(nextRecording){
					message.info('开始录音...',2);
					startAudio()
				}else{
					stopAudio()
				}
				recording.value = nextRecording;
			},
		} : false
	})

	const setFinishFunc = (cb:(str:string)=>void)=>{
		cbFinish = cb
	}
	//开始录音
	const startAudio = ()=>{
		navigator.mediaDevices.getUserMedia({ audio: true })
			.then(stream => {
				mediaRecorder = new MediaRecorder(stream);
				mediaRecorder.ondataavailable = (event:any) => {
					recordedChunks.push(event.data);
				};
				mediaRecorder.onstop = () => {
					//console.log('Recording stopped.');
					const hide = message.loading('语音转文字...,',0);
					const audioBlob = new Blob(recordedChunks, { type: 'audio/mp3' });
					apiAiFetch.uploadAudio( props.source||'chat',
						audioBlob,
						(body:any)=>{
							//console.log(body);
							mediaRecorder=null;
							recordedChunks=[]
							setTimeout(hide,0)
							if(cbFinish) cbFinish(body.text)
							//value.value = body.text
						},
						()=>{
							mediaRecorder=null;
							recordedChunks=[]
							setTimeout(hide,0)
						}
					);
				}
				mediaRecorder.start();
				//console.log('Recording started.');
			})
			.catch(error => console.error('Error accessing media devices.', error));
	}

	//结束录音
	const stopAudio = ()=>{
		mediaRecorder.stop();
	}

	return {
		recording, //data
		speechOption, //computed
		setFinishFunc, //methods
	}
}